package com.dhcc.sds.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.cdc.busi.entity.CdcDiagnosisEntity;
import com.dhcc.cdc.busi.service.ICdcDiagnosisService;
import com.dhcc.cdc.sys.cache.config.CdcConfigCache;
import com.dhcc.cdc.sys.entity.ConfigurationEntity;
import com.dhcc.cdc.sys.entity.DictionaryEntity;
import com.dhcc.cdc.sys.service.IConfigurationService;
import com.dhcc.cdc.sys.service.IDictionaryService;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.SpringContextHolder;
import com.dhcc.sds.api.service.IDocApiService;
import com.dhcc.sds.base.entity.SdsExpressEntity;
import com.dhcc.sds.base.entity.SdsQcentityRuleEntity;
import com.dhcc.sds.base.function.GetEntrySrv;
import com.dhcc.sds.base.service.ISdsCommonService;
import com.dhcc.sds.base.service.ISdsExpressService;
import com.dhcc.sds.base.service.ISdsQcentityRuleService;
import com.dhcc.sds.busi.dao.SdsFillByDoctorMapper;
import com.dhcc.sds.busi.dto.SdsFillByDoctorDto;
import com.dhcc.sds.busi.entity.SdsQcincaseEntity;
import com.dhcc.sds.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.*;

/**
 * @version 1.0 DHCC
 * @Description: 描述
 * @Project Name:
 * @Package Name:
 * @File Name:
 * @author:sunyingjie
 * @date:
 * @Copyright: (c) DHCC All rights reserved.
 */
@Service("docApiService")
public class DocApiServiceImpl implements IDocApiService {
    @Autowired
    private SdsFillByDoctorMapper sdsFillByDoctorMapper;

    @Autowired
    private IDictionaryService dictionaryService;

    @Autowired
    private ISdsCommonService sdsCommonService;

    @Autowired
    private IConfigurationService configurationService;
    
    @Autowired
    private ISdsQcentityRuleService sdsQcentityRuleService;

    @Autowired
    private ISdsExpressService sdsExpressService;

    @Autowired
    private ICdcDiagnosisService cdcDiagnosisService;

    @Override
    public List<SdsQcincaseEntity> page(Page<SdsQcincaseEntity> page, Map<String, Object> map) {
        List<SdsQcincaseEntity> result = new ArrayList<>();

        if (CommonUtil.isEmpty(map.get("status"))) {
            return result;
        }

        Object entityId = map.get("entityId");
        if (CommonUtil.isEmpty(entityId)) {
            //按医生填报查询 可以允许病种id为空
            //return result;
        }
        Object status = map.get("status");
        if (CommonUtil.isNotEmpty(map.get("locId"))) {
            String locId = map.get("locId").toString();
            // 查询科室ID在本系统内的ID
            List<String> deptIds = new ArrayList<>();
            deptIds.add(locId);
            map.put("userLinkDepts", deptIds);
        }

        // 单病种医生是否可以直接上报配置
        String formCheckType = CdcConfigCache.me().getValueByKey("SDS", "SDFormCheckType");
        String sqlStr = "";
        if (CommonUtil.isNotEmpty(status)) {
            switch (status.toString()) {
                case "notReported":
                    if (CommonUtil.equals(formCheckType, "Y")) {
                        sqlStr = "and (state = 'I' or state = 'Save' or state = 'Submit' or state = 'Check') ";
                    } else {
                        sqlStr = "and (state = 'I' or state = 'Save') ";
                    }
                    break;
                case "backed":
                    sqlStr = "and state = 'Back' ";
                    break;
                case "reported":
                    sqlStr = "and state = 'Up' ";
                    break;
                case "notChecked":
                    sqlStr = "and state = 'Submit' ";
                    break;
                case "checked":
                    sqlStr = "and state = 'Check' ";
                    break;
                case "uploadSuccess":
                    sqlStr = "and state = 'Up' and report_state = 2";
                    break;
                case "uploadFailure":
                    sqlStr = "and state = 'Up' and report_state = 4";
                    break;
                default:
                    break;
            }
            map.put("stateSql", sqlStr);
        }
        result = sdsFillByDoctorMapper.selectMrlist(page, map);
        String baseDateForDelayed = CdcConfigCache.me().getValueByKey("SDS", "BaseDateForDelayed", "2");
        for (SdsQcincaseEntity sdsQcincaseEntity : result) {
            if (CommonUtil.equals(baseDateForDelayed, "1")) {
                if (CommonUtil.isNotEmpty(sdsQcincaseEntity.getDishDate())) {
                    if (CommonUtil.notEquals(sdsQcincaseEntity.getState(), "Up")) {
                        sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(new Date(), sdsQcincaseEntity.getDishDate(), "d")));
                    } else {
                        sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(sdsQcincaseEntity.getReportDate(), sdsQcincaseEntity.getDishDate(), "d")));
                    }
                }
            } else if (CommonUtil.equals(baseDateForDelayed, "2")) {
                if (CommonUtil.isNotEmpty(sdsQcincaseEntity.getCodeDate())) {
                    if (CommonUtil.notEquals(sdsQcincaseEntity.getState(), "Up")) {
                        sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(new Date(), sdsQcincaseEntity.getCodeDate(), "d")));
                    } else {
                        sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(sdsQcincaseEntity.getReportDate(), sdsQcincaseEntity.getCodeDate(), "d")));
                    }
                }
            } else if (CommonUtil.equals(baseDateForDelayed, "3")) {
                if (CommonUtil.isNotEmpty(sdsQcincaseEntity.getInDate())) {
                    if (CommonUtil.notEquals(sdsQcincaseEntity.getState(), "Up")) {
                        sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(new Date(), sdsQcincaseEntity.getInDate(), "d")));
                    } else {
                        sdsQcincaseEntity.setReportDelayDays(Math.toIntExact(DateUtil.getDateCompare(sdsQcincaseEntity.getReportDate(), sdsQcincaseEntity.getInDate(), "d")));
                    }
                }
            }

//            String reason = sdsQcincaseEntity.getReason();
//            if (CommonUtil.isNotEmpty(reason)) {
//                String[] reasonSplit = reason.split(",");
//                String reaSonStr = "";
//                for (String reasonId : reasonSplit) {
//                    if (CommonUtil.isNotEmpty(reasonId)) {
//                        SdsQcentityRuleEntity sdsQcentityRuleEntity = sdsQcentityRuleService.selectById(reasonId);
//                        SdsExpressEntity sdsExpressEntity = sdsExpressService.selectById(sdsQcentityRuleEntity.getExpressId());
//                        if (!StringUtils.isEmpty(sdsExpressEntity)) {
//                            try {
//                                Class<?> c = Class.forName("com.dhcc.sds.base.function.GetEntrySrv");
//                                GetEntrySrv getEntrySrv = SpringContextHolder.getBean("getEntrySrv");
//                                String methodName = sdsExpressEntity.getExpress() + "Detail";
//                                Method method = c.getMethod(methodName, Long.class, String.class);
//                                String ret = (String) method.invoke(getEntrySrv, sdsQcincaseEntity.getEpisodeId(), sdsQcentityRuleEntity.getParam());
//                                reaSonStr += ret + "\n\n";
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }
//                }
//                if (reaSonStr.length() != 0) {
//                    reaSonStr = reaSonStr.substring(0, reaSonStr.length() - 1);
//                }
//                sdsQcincaseEntity.setReason(reaSonStr);
//            }
            sdsQcincaseEntity.setReason("");
            HashMap<String, Object> qryMap = new HashMap<>();
            qryMap.put("episode_id", sdsQcincaseEntity.getEpisodeId());
            qryMap.put("bus_diag_type_id", "1382251829770014721");
            List<CdcDiagnosisEntity> cdcDiagnosisEntities = this.cdcDiagnosisService.selectByMap(qryMap);
            if (cdcDiagnosisEntities.size() != 0) {
                String description = cdcDiagnosisEntities.get(0).getDescription();
                sdsQcincaseEntity.setReason(description);
            }
        }

        return result;
    }

    @Override
    public Map<String, Object> listByDate(Map<String, Object> params) {
        Map<String, Object> entityMap = new HashMap();
        // 查询登录用户关联科室
        String locId = params.get("locId").toString();
        List<String> deptIds = new ArrayList<>();
        deptIds.add(locId);
        params.put("userLinkDepts", deptIds);
        List<Map<String, Object>> mrlist = sdsFillByDoctorMapper.getMrlistOfDept(params);

        // 单病种医生是否可以直接上报配置
        String formCheckType = CdcConfigCache.me().getValueByKey("SDS", "SDFormCheckType");

        //控制展现维度
        String dimType = params.get("dimType").toString();
        SdsFillByDoctorDto entityDto;
        for (Map<String, Object> mrMap : mrlist) {
            Long entityId = Long.valueOf(mrMap.get("entityId").toString());

            String entityAbbrev = mrMap.get("entityAbbrev").toString();
            String doctorName =mrMap.get("doctorName").toString();
            //默认维护为病种
            String targetName = entityAbbrev;
            if (CommonUtil.equals(dimType,"doctor")) { targetName = doctorName;}
            String entityName = mrMap.get("entityName").toString();
            Integer entityStatus = (Integer) mrMap.get("entityStatus");
            if (entityMap.containsKey(targetName)) {
                entityDto = (SdsFillByDoctorDto) entityMap.get(targetName);
            } else {
                entityDto = new SdsFillByDoctorDto();
                entityDto.setEntityId(entityId);
                entityDto.setAbbrev(entityAbbrev);
                entityDto.setBtDesc(entityName);
                entityDto.setIsActive(entityStatus);
                entityDto.setDoctorName(doctorName);
            }
            this.calcEntityDetail(mrMap, entityDto, formCheckType);
            entityMap.put(targetName, entityDto);
        }
        entityMap.put("patientNum", mrlist.size());
        return entityMap;
    }

    private void calcEntityDetail(Map<String, Object> mrMap, SdsFillByDoctorDto entityDto, String formCheckType) {
        String status = mrMap.get("state").toString();
        if ("I".equals(status) || "Save".equals(status)) {
            //待填报
            entityDto.setNotReported(entityDto.getNotReported() + 1);
        } else if ("Back".equals(status)) {
            //已退回
            entityDto.setBacked(entityDto.getBacked() + 1);
        } else if ("Up".equals(status)) {
            //已上报
            entityDto.setReported(entityDto.getReported() + 1);
            if (mrMap.get("reportState") == null) {

            } else if (CommonUtil.equals(mrMap.get("reportState"),2)) {
                // 上传国家平台成功
                entityDto.setUploadSuccess(entityDto.getUploadSuccess() + 1);
            } else if (CommonUtil.equals(mrMap.get("reportState"),4)) {
                // 上传国家平台失败
                entityDto.setUploadFailure(entityDto.getUploadFailure() + 1);
            }
        } else if ("Check".equals(status)) {
            // 如果允许医生直接上报，则没有审核流程
            if (CommonUtil.equals(formCheckType, "Y")) {
                //待填报
                entityDto.setNotReported(entityDto.getNotReported() + 1);
            } else {
                // 已审核
                entityDto.setChecked(entityDto.getChecked() + 1);
            }
        } else if ("Submit".equals(status)) {
            // 如果允许医生直接上报，则没有审核流程
            if (CommonUtil.equals(formCheckType, "Y")) {
                //待填报
                entityDto.setNotReported(entityDto.getNotReported() + 1);
            } else {
                // 未审核
                entityDto.setNotChecked(entityDto.getNotChecked() + 1);
            }
        }
        // 测试上报例数
        if (CommonUtil.equals(mrMap.get("testFlg"), 1)) {
            entityDto.setTestCount(entityDto.getTestCount() + 1);
        }
        // 病种入组人数
        entityDto.setPatientNum(entityDto.getPatientNum() + 1);
        // 住院总天数
        if (CommonUtil.isNotEmpty(mrMap.get("admDays"))) {
            int admDays = Integer.valueOf(mrMap.get("admDays").toString());
            entityDto.setTotalDays(entityDto.getTotalDays() + admDays);
        }
        // 住院总费用
        if (CommonUtil.isNotEmpty(mrMap.get("costs"))) {
            BigDecimal costs = new BigDecimal(mrMap.get("costs").toString());
            entityDto.setTotalCost(entityDto.getTotalCost().add(costs));
        }
    }

    @Override
    public JSONObject getStatusMapByType(String type) {
        JSONObject jsObj = new JSONObject();
        jsObj.put("", "");
        List<DictionaryEntity> sds = dictionaryService.queryByTypeCode("SDS", type);
        for (DictionaryEntity dic : sds) {
            jsObj.put(dic.getCode(), dic.getDescription());
        }
        return jsObj;
    }
}
